import datetime
from flask_login import UserMixin
from sqlalchemy import DateTime, Numeric

from applications.exts import db

# 收货地址
class Wx_User_Address(db.Model, UserMixin):
    __tablename__ = 'wx_user_address'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    openid = db.Column(db.String(60),db.ForeignKey('wx_user.openid'), nullable=False, comment='设置外建')
    username = db.Column(db.String(20), comment='收货地址的用户名')
    address = db.Column(db.String(90), comment='收货地址')
    avatar = db.Column(db.String(255), comment='头像', default="/static/admin/admin/images/avatar.jpg")
    phone = db.Column(db.String(11), comment='手机号')
    default = db.Column(db.Integer, default=1, comment='是否设置维默认地址，1是默认')
    create_at = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')

    def to_dict(self):
        res = {}
        for col in self.__table__.columns:
            if isinstance(col.type, DateTime):  # 判断类型是否为DateTime
                if not getattr(self, col.name):  # 判断实例中该字段是否有值
                    value = ""
                else:  # 进行格式转换
                    value = getattr(self, col.name).strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(col.type, Numeric):  # 判断类型是否为Numeric
                value = float(getattr(self, col.name))  # 进行格式转换
            else:  # 剩余的直接取值
                value = getattr(self, col.name)
            res[col.name] = value
        return res